package com.yimin.floatball.util

import android.accessibilityservice.AccessibilityService
import android.content.Context
import android.provider.Settings
import android.util.Log
import com.yimin.floatball.TAG

/**
 * 执行返回，下拉通知栏等动作，必须开启无障碍服务
 */
object AccessibilityUtil {

    fun doBack(service: AccessibilityService) {
        service.performGlobalAction(AccessibilityService.GLOBAL_ACTION_BACK)
    }

    fun doPullDown(service: AccessibilityService) {
        service.performGlobalAction(AccessibilityService.GLOBAL_ACTION_NOTIFICATIONS)
    }

    fun doPullUp(service: AccessibilityService) {
        service.performGlobalAction(AccessibilityService.GLOBAL_ACTION_HOME)
    }

    fun doLeftOrRight(service: AccessibilityService) {
        service.performGlobalAction(AccessibilityService.GLOBAL_ACTION_RECENTS)
    }

    fun isAccessibilitySettingsOn(context: Context): Boolean {
        val accessibilityEnabled = Settings.Secure.getInt(
            context.contentResolver,
            Settings.Secure.ACCESSIBILITY_ENABLED
        ).also {
            Log.d(TAG, "accessibilityEnabled: ${it}")
        }

        return if (accessibilityEnabled == 1) {
            val services = Settings.Secure.getString(
                context.contentResolver,
                Settings.Secure.ENABLED_ACCESSIBILITY_SERVICES
            ).also {
                Log.d(TAG, "services: ${it}")
            }
            services?.lowercase()?.contains(context.packageName.lowercase()) == true
        } else {
            false
        }
    }
}